<?php

namespace app\admin\controller\dev;

use app\admin\annotation\common\Auth;
use app\admin\controller\Admin;
use app\admin\model\dev\Prop as PropModel;
use app\admin\validate\dev\Prop as PropValidate;
use app\admin\service\common\SortableService;
use app\admin\service\dev\FieldService;
use app\admin\service\dev\PropService;
use app\common\Constants;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;


class Prop extends Admin
{
    #[Auth('dev:prop:index')]
    public function index(): \think\response\Json
    {
        $params = $this->request->post();
        try {
            validate(PropValidate::class)
                ->scene('index')
                ->check($params);
            $query = PropModel::withPerms();
            // 设置了keyword且不为空
            $query->when(isset($params['keyword']), function ($q) use ($params) {
                $keyword = str_replace(['%', '_'], ['\%', '\_'], $params['keyword']);
                $q->where('label|value', 'like', '%' . $keyword . '%');
            });
            $query->when(isset($params['type']), function ($q) use ($params) {
                $q->where('type', '=', $params['type']);
            });
            $query->when(isset($params['for_template']), function ($q) use ($params) {
                $q->where('for_template', '=', $params['for_template']);
            });
            $query->when(isset($params['status']), function ($q) use ($params) {
                $q->where('status', '=', $params['status']);
            });
            // 排序
            $order_by = sort_rules($params['order_by'] ?? 'sort|asc');
            $query->order($order_by);
            // 分页
            $page_size = $params['page_size'] ?? 10;
            $current_page = $params['current_page'] ?? 1;
            $list = $query->paginate(['list_rows' => $page_size, 'page' => $current_page])->toArray();
            $list['sort'] = $order_by;
            return $this->success(['data' => $list]);
        } catch (\think\Exception\ValidateException $ve) {
            return $this->error(['message' => $ve->getMessage()]);
        } catch (\Exception $e) {
            throw $e;
        }
    }


    /**
     * 新增
     * @return \think\response\Json
     */
    #[Auth('dev:prop:add')]
    public function add(): \think\response\Json
    {
        try {
            $fields = FieldService::getDmlFields('DevProp', 'add');
            $data = $this->request->only($fields, 'post');
            validate(PropValidate::class)
                ->scene('add')
                ->check($data);
            PropModel::create($data);
            return $this->success();
        } catch (\think\Exception\ValidateException $ve) {
            return $this->error(['message' => $ve->getMessage()]);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 更新
     * @return \think\response\Json
     */
    #[Auth('dev:prop:update')]
    public function update(): \think\response\Json
    {
        try {
            $fields = FieldService::getDmlFields('DevProp', 'update');
            $data = $this->request->only($fields, 'post');
            validate(PropValidate::class)
                ->scene('update')
                ->check($data);
            $result = PropModel::update($data);
            if (!$result) {
                throw new \Exception(Constants::E_COMMON_UPDATE_DATA_FAILED);
            }
            return $this->success();
        } catch (\think\Exception\ValidateException $ve) {
            return $this->error(['message' => $ve->getMessage()]);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 查询表单数据
     * @return \think\response\Json
     */
    #[Auth('dev:prop:update')]
    public function getFormData(): \think\response\Json
    {

        $id = $this->request->param('id');
        if (!$id) {
            return $this->error(['message' => Constants::E_COMMON_INVALID_PARAM]);
        }
        $result = PropModel::find($id);
        if (!$result) {
            return $this->error(['message' => Constants::E_COMMON_RECORD_NOT_FOUND]);
        }
        return $this->success(['data' => $result]);

    }

    /**
     * 详情
     * @return \think\response\Json
     */
    #[Auth('dev:prop:detail')]
    public function detail(): \think\response\Json
    {

        $id = $this->request->param('id');
        if (!$id) {
            return $this->error(['message' => Constants::E_COMMON_INVALID_PARAM]);
        }
        $result = PropModel::find($id);
        if (!$result) {
            return $this->error(['message' => Constants::E_COMMON_RECORD_NOT_FOUND]);
        }
        return $this->success(['data' => $result]);

    }

    /**
     * 删除
     * @return \think\response\Json
     */
    #[Auth('dev:prop:delete')]
    public function delete(): \think\response\Json
    {
        try {
            $ids = $this->request->post('id/a');
            $ids = array_map('intval', $ids);
            $ids = array_filter($ids, function ($id) {
                return $id > 0;
            });
            if (empty($ids)) {
                return $this->error(['message' => Constants::E_COMMON_INVALID_PARAM]);
            }
            Db::startTrans();
            $deleteCount = PropModel::destroy(function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            });
            Db::commit();
            if ($deleteCount > 0) {
                return $this->success(['data' => $deleteCount]);
            } else {
                return $this->error(['message' => Constants::E_COMMON_RECORD_NOT_FOUND]);
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }


    /**
     * 修改任意字段
     * @return \think\response\Json
     *
     */
    #[Auth('dev:prop:modify')]
    public function modify(): \think\response\Json
    {

        $post = $this->request->post();
        $keys = array_keys($post);
        $array = array_values(array_filter($keys, fn($v) => $v !== 'id'));
        $field = $array[0];
        if (!$post['id']) {
            return $this->error(['message' => Constants::E_COMMON_INVALID_PARAM]);
        }
        if (!in_array($field, ['status'])) {
            return $this->error(['message' => Constants::E_COMMON_FORBIDDEN]);
        }
        $model = PropModel::find($post['id']);
        if (!$model) {
            return $this->error(['message' => Constants::E_COMMON_RECORD_NOT_FOUND]);
        }
        $model[$field] = $post[$field];
        $result = $model->save();
        if (!$result) {
            throw new \Exception('更新状态失败');
        }
        return $this->success();

    }


    /**
     *  拖拽排序
     * @return \think\response\Json
     */
    #[Auth('dev:prop:drag')]
    public function drag(): \think\response\Json
    {

        $fields = "newId,oldId,dragPos,orderBy";
        $data = $this->request->only(explode(',', $fields), 'post');
        SortableService::sort('dev_prop', $data);
        return $this->success();

    }


}